import tnx from '@/tnx.js';

/**
 * 泛型
 */
export default class GenericType {

    /**
     * 类型参数，声明时一般为T，指定时可能为?或空
     * @type {string}
     */
    parameter = '';
    /**
     * true-表示extends关系，false-表示super关系，null-没有关系
     * @type {Boolean}
     */
    extended = null;
    typeId = '';
    arrayed = false;

    static of(object) {
        if (typeof object !== 'object') {
            return undefined;
        }
        let type = new GenericType();
        type.update(object);
        return type;
    }

    update(object) {
        tnx.util.object.rewriteSimpleDefined(this, object, ['extended']);
        if (typeof object === 'object') {
            if (object.extended !== undefined) {
                if (object.extended === null) {
                    this.extended = null;
                } else if (typeof object.extended === 'string') {
                    if (object.extended === '') {
                        this.extended = null;
                    } else {
                        this.extended = object.extended === 'true';
                    }
                } else {
                    this.extended = !!object.extended;
                }
            }
            if (object.arrayed !== undefined) {
                if (typeof object.arrayed === 'string') {
                    this.arrayed = object.arrayed === 'true';
                }
            }
        }
        return this;
    }

    clone() {
        return GenericType.of(this);
    }

    equals(other) {
        if (!other || !(other instanceof GenericType)) {
            return false;
        }
        return this.parameter === other.parameter && this.extended === other.extended && this.typeId === other.typeId;
    }

}
